/**
 * 定义页面对应的后台处理类完整路径。
 */
var clsUrl = basePath + 'JarpListener?className=cn.com.zsc.cm.CostManage';
var status;

Ext.onReady(function(){
	Ext.QuickTips.init();
	
	/**
	 * 费用分类数据源
	 */
	var typeStore=new Ext.data.Store({
		proxy : new Ext.data.HttpProxy({
			url : comboBoxUrl + '29'
		}),
		reader : new Ext.data.JsonReader({
			fields : [
			{name:'CL_CODE'},
			{name:'CL_NAME'}
		]
		}),
		autoLoad : true
	});
	
	/**
	 * 费用分类控件
	 */
	var typeComboBox = new Ext.form.ComboBox({
		fieldLabel : '费用分类',
		id : 'type',
		width : 100,
		displayField : 'CL_NAME',
		valueField : 'CL_CODE',
		emptyText : '请选择',
		store:typeStore,
		mode : 'local',
		editable  : false,
		triggerAction : 'all',
		selectOnFocus : true
	});
	
	/**
	 * 发生时间控件
	 */
	var occurDate = new Ext.form.DateField({
		id:'occurDate',
        fieldLabel:"发生时间",
        name:'occurDate',
        format:'Y-m-d',
        editable:false,
        width:100
    });
    
	var storereader= new Ext.data.JsonReader({
		//为分页增加
		root : 'results',
        totalProperty : 'totalCount',
        
    	fields:[
    		{name :'ID'},
    		{name :'CNAME'},
    		{name :'CTYPE'},
    		{name :'TYPE'},
			{name :'AMOUNT'},
			{name :'DATE'},
			{name :'EP'},
			{name :'REMARKED'},
			
			{name:'SHOW_TYPE'},
			{name:'SHOW_EP'}
    	]
	});
		
	/**
	 * 查询分页数据
	 */
	var store = new Ext.data.Store({
		reader:storereader,
		proxy:new Ext.data.HttpProxy({
			url:clsUrl+'&methodName=getCost&&paramCount=3'
		})
	});
     
	/**
	 * 分页Panel
	 */
	var toolpanel = new Ext.PagingToolbar({
        pageSize:20,
        store:store,
        storeParams : {
                className : 'cn.com.zsc.cm.CostManage',
                methodName : 'getCost',
                paramCount : '2',
                param_0 : '0',
                param_1 : '20'
            },
            paramNames : {
                start : 'param_0',
                limit : 'param_1'
            },
        displayInfo: true,
        displayMsg: '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
        emptyMsg: '没有记录'
    });
                
	/**
	 * 用户列表
	 */
	var basegrid = new Ext.grid.GridPanel( {
		id :'basegrid',
		store :store,
		split :true,
		bodyStyle:'5px 15px 0',
		region :'center',
		border :false,
		enableColumnMove:false,                                           
	  	enableHdMenu:false,
		frame :false,
		autoScroll :true,
		viewConfig: {
        	forceFit: true
    	},
    	columns: [
     	            new Ext.grid.RowNumberer(),
    	          	{id:'cName',name:'cName', header:'费用名称',sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize :false, dataIndex: 'CNAME'},
    	          	{header:'费用分类',sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize :false, dataIndex: 'SHOW_TYPE'},
    	          	{id:'type',name:'type',header:'费用分类',sortable:true,hidden:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize :false, dataIndex: 'TYPE'},
    	          	{id:'amount',name:'amount',header:'金额',sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize :false,dataIndex: 'AMOUNT'},
    	          	{id:'date',name:'date',header:'发生时间',sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize :false,dataIndex: 'DATE'},
    	          	{id:'ep',name:'ep',header:'录入人',sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize :false,dataIndex: 'SHOW_EP'},
    	          	{id:'remarked',name:'remarked',header:'备注',sortable:true,enableColumnMove:false,enableHdMenu:false,enableColumnResize :false, dataIndex: 'REMARKED'}
    	],
    	tbar:[
	    	     {
		    	     text:'新增',
		    	     iconCls:'add',
		      	   	 handler:function(){
		      	   	 	status=1;
		      	   	 	formPanel.getForm().reset();
		      	   	 	Ext.getCmp("ep").setValue(curUserName);
		      	   	 	
		      	   	 	var date = new Date();
						var year = date.getYear();
						var month = date.getMonth()+1;
						var day = date.getDate();
						var hours = date.getHours();
						var minutes = date.getMinutes();
						var seconds = date.getSeconds();
						
						var now = year;
						
						now += ((month < 10) ? "-0" : "-") + month+"";
						now += ((day < 10) ? "-0" : "-") + day+"";
						
						Ext.getCmp("occurDate").setValue(now);
						
		      	   	 	win.setTitle("新增间接成本");
		      	   	 	win.show();
		    	     }
	      	   	},
	      	   	'-',
	      	   	{
		      	   	text:'修改',
		      	   	iconCls:'modify',
		      	   	handler:function(){
	      	   			status=2;
	      	   			var record = basegrid.getSelectionModel().getSelected(); 
	   		       		if(!record){   
			   		        Ext.Msg.show({
										title : '提示',
										width:210,
										msg : '请选择要修改的数据!',
										buttons : Ext.Msg.OK,
										icon : Ext.Msg.ERROR
									});
						}else{
			      	   		if(record){
								win.setTitle("修改间接成本");
			            	   	win.show();
			            	   	
			            	   	var record = basegrid.getSelectionModel().getSelected();
			
								Ext.getCmp("id").setValue(record.data.ID);
								Ext.getCmp("cName").setValue(record.data.CNAME);
								Ext.getCmp("type").setValue(record.data.TYPE);
								Ext.getCmp("amount").setValue(record.data.AMOUNT);
								Ext.getCmp("occurDate").setValue(record.data.DATE);
								Ext.getCmp("ep").setValue(curUserName);
								Ext.getCmp("remarked").setValue(record.data.REMARKED);
			            	}     
		      	   		}
	      	   		}
	      	   	},
	      	   	'-',
	      	   	{
		      	   	text:'删除',
		      	   	iconCls:'delete',
		      	   	handler:del
	      	   	}
	      	   	
 	  ],
 	  bbar:toolpanel
	});
	
	var newType = new Ext.form.TextField({fieldLabel:'费用分类',labelWidth:100,id:'newType',width:99});
	/**
	 * formPanel
	 */
	var formPanel = new Ext.FormPanel({
		bodyStyle:'padding:20px 15px 0',
		region:'center',
		layout:'form',
		frame:true,
		labelWidth:100,
		labelAlign:'right',
		
		items:[
			   {fieldLabel: '成本编号',width:200,name:'id',id:'id',xtype:'textfield',hideLabel:true,hidden:true},
		       {fieldLabel: '费用名称',width:200,name:'cName',id:'cName',xtype:'textfield'},
		       {
		           layout : 'column',
				   labelAlign : 'right',
				   items :[{
				        layout : 'form',
						labelWidth : 100,
						labelAlign : 'right',
						columnWidth : .62,
						items : [typeComboBox,newType]
				   },{
				   		layout : 'form',
						labelWidth : 0,
						labelAlign : 'right',
						columnWidth : .38,
						items : [{
									text: '新增分类',width:50,name:'display',id:'display',xtype:'button',
									handler:function(){
										if(newType.disabled) {
											// 显示文本框
										    newType.enable();
										    newType.getEl().up('.x-form-item').setDisplayed(true);
										    
										    // 隐藏下拉框
										    Ext.getCmp('type').setValue("");
										    Ext.getCmp('type').disable();
										    Ext.getCmp('type').getEl().up('.x-form-item').setDisplayed(false);
										    
										    // 设置按钮文字
										    Ext.getCmp('display').setText('选择分类');
										} else {
											// 显示下拉框
											Ext.getCmp('type').enable();
											Ext.getCmp('type').getEl().up('.x-form-item').setDisplayed(true);
											
											// 隐藏文本框
											newType.setValue("");
										    newType.disable();  
											newType.getEl().up('.x-form-item').setDisplayed(false);
											
											// 设置按钮文字
											Ext.getCmp('display').setText('新增分类');
										}
									},
									listeners:{'render': function() {
										// 隐藏文本框
										newType.disable();  
										newType.getEl().up('.x-form-item').setDisplayed(false);
									}
								 }	
						}]
				   }]
		       },
//		       newType,
		       {fieldLabel: '金额',width:200,name:'amount',id:'amount',xtype:'numberfield',allowNegative:false},
			   occurDate,
			   {fieldLabel: '录入人',width:200,name:'ep',id:'ep',xtype:'textfield',disabled:true},
			   {fieldLabel: '备注',width:200,name:'remarked',id:'remarked',xtype:'textarea'}
		]
	});
	
	/**
	 * 保存取消按钮
	 */
	var win = new Ext.Window({
		title:'新增间接成本',
		width:400,
		height:350,
		layout:'border',
		closeAction:'hide',
		modal:true,
		draggable:false,
		resizable:false,
		tbar:[
		      {
		    	  text:'保存',
		    	  iconCls:'save',
		    	  handler:judge
		      },
		      '-',
		      {
		    	  text:'取消',
		    	  iconCls:'cancel',
		    	  handler:function(){
      	   			win.hide();
		      	  }
		      }
		],
		items:[formPanel]
	});
	
	var mainPanel = new Ext.Panel({
            id: 'mainPanel',
            region:'center',
            split:true,
            border:false,
            frame:true,
            layout: 'border',  
            items:[basegrid]
    });
    
	var viewport = new Ext.Viewport( {
		layout:'border',
		items: [mainPanel ]
	});
	
	/**
	 * 判断是新增还是修改
	 */
	function judge(){
		if(status==1){
			save();
		}else if(status==2){
			update();
		}
	}
	
	/**
	 * 新增用户
	 */
	function save(){
		if(!saveValidate()){
		    return;	
		}
			
		var obj = new Object();
		
		obj.cName = Ext.getCmp("cName").getValue();
		obj.cType = 105;
		obj.type = Ext.getCmp("type").getValue();
		obj.amount = Ext.getCmp("amount").getValue();
		obj.date = Ext.getCmp("occurDate").getValue();
		obj.ep = curUserID;
		obj.remarked = Ext.getCmp("remarked").getValue();
		obj.newType = Ext.getCmp("newType").getValue();
		
		var url=clsUrl+'&methodName=insertCost&paramCount=0'
		
    	httpReq=null;
		httpReq = getXMLHttpRequest();
    	httpReq.onreadystatechange = onSaveRtn;
		httpReq.open("POST",url, true);
		httpReq.send(Ext.util.JSON.encode(obj));
	}
	
	function onSaveRtn(){
		if(httpReq.readyState == 4){
		   	if(httpReq.status == 200){
		   		if(httpReq.responseText == "success"){
		   			Ext.Msg.show({   
		    	   		title : '成功提示',
		    	   		width:200,
		   				msg : '保存成功！',  
			       		buttons : Ext.Msg.OK,   
			       		icon : Ext.Msg.INFO   
		   			});
					
		   			store.reload();
                    formPanel.getForm().reset();
		   			win.hide();
		   			httpReq=null;
		   			
		   			// 显示下拉框
					Ext.getCmp('type').enable();
					Ext.getCmp('type').getEl().up('.x-form-item').setDisplayed(true);
					
					// 隐藏文本框
					newType.setValue("");
				    newType.disable();  
					newType.getEl().up('.x-form-item').setDisplayed(false);
					
					// 设置按钮文字
					Ext.getCmp('display').setText('新增分类');
					
					// 刷新下拉框store
					typeStore.reload();
		   		}else{
		   			Ext.Msg.show({   
		    	   		title : '错误提示',
		    	   		width:200,
		   				msg :httpReq.responseText,  
			       		buttons : Ext.Msg.OK,   
			       		icon : Ext.Msg.ERROR   
		   			});  
		   			httpReq=null;
		   		}
		   	}
		}
	}
	
	/**
	 * 修改用户
	 */
	function update(){
		if(!saveValidate()){
			return ;
		}
		
		var obj = new Object();
		
		obj.id = Ext.getCmp("id").getValue();
		obj.cName = Ext.getCmp("cName").getValue();
		obj.type = Ext.getCmp("type").getValue();
		obj.amount = Ext.getCmp("amount").getValue();
		obj.date = Ext.getCmp("occurDate").getValue();
		obj.ep = curUserID;
		obj.remarked = Ext.getCmp("remarked").getValue();
		obj.newType = Ext.getCmp("newType").getValue();
				
		var url=clsUrl+'&methodName=updateCost&paramCount=0'
		
    	httpReq=null;
		httpReq = getXMLHttpRequest();
    	httpReq.onreadystatechange = onUpdateRtn;
		httpReq.open("POST",url, true);
		httpReq.send(Ext.util.JSON.encode(obj));
	}
	
	function onUpdateRtn(){
		if(httpReq.readyState == 4){
		   	if(httpReq.status == 200){
		   		if(httpReq.responseText == "success"){
		   			Ext.Msg.show({   
		    	   		title : '成功提示',
		    	   		width:200,
		   				msg : '保存成功！',  
			       		buttons : Ext.Msg.OK,   
			       		icon : Ext.Msg.INFO   
		   			});
		   			store.reload();
		   		    formPanel.getForm().reset();
		   			win.hide();
		   			httpReq=null;
		   			
		   			
	   				// 显示下拉框
					Ext.getCmp('type').enable();
					Ext.getCmp('type').getEl().up('.x-form-item').setDisplayed(true);
					
					// 隐藏文本框
					newType.setValue("");
				    newType.disable();  
					newType.getEl().up('.x-form-item').setDisplayed(false);
					
					// 设置按钮文字
					Ext.getCmp('display').setText('新增分类');
					
					// 刷新下拉框store
					typeStore.reload();
		   		}else{
		   			Ext.Msg.show({   
		    	   		title : '错误提示',
		    	   		width:200,
		   				msg :httpReq.responseText,  
			       		buttons : Ext.Msg.OK,   
			       		icon : Ext.Msg.ERROR   
		   			});  
		   			httpReq=null;
		   		}
		   	}
		}
	}
	
	/**
	 * 删除成本
	 */
	function del(){
		var record = basegrid.getSelectionModel().getSelected();
		
		if(!record){
			Ext.Msg.show({
				title:'提示',
				width:210,
				msg:'请选择要删除的数据',
				buttons:Ext.Msg.OK,
				icon: Ext.Msg.ERROR 
			});	
		}	
		
		if(record){
			Ext.Msg.show({
				title:'提示',
				width:200,
				msg:'确定要删除数据！', 
				buttons: Ext.Msg.YESNO,
	            icon: Ext.MessageBox.QUESTION,
				fn:function(btn){
					if( "yes" == btn){
						delProc()
					}
				}
			});
			
		}
					
	}
	
	function delProc(){
		var record = basegrid.getSelectionModel().getSelected();
		 
		var obj = new Object();
		obj.id = record.data.ID;
		
		var url=clsUrl+'&methodName=deleteCost&paramCount=0'
		
    	httpReq=null;
		httpReq = getXMLHttpRequest();
    	httpReq.onreadystatechange = onDelRtn;
		httpReq.open("POST",url, true);
		httpReq.send(Ext.util.JSON.encode(obj));
	}
	
	function onDelRtn(){
		if(httpReq.readyState == 4){
		   	if(httpReq.status == 200){
		   		if(httpReq.responseText == "success"){
		   			Ext.Msg.show({   
		    	   		title : '成功提示',
		    	   		width:200,
		   				msg : '删除成功！',  
			       		buttons : Ext.Msg.OK,   
			       		icon : Ext.Msg.INFO   
		   			});
		   			store.reload();
		   			httpReq=null;
		   		}else{
		   			Ext.Msg.show({   
		    	   		title : '错误提示',
		    	   		width:200,
		   				msg :httpReq.responseText,  
			       		buttons : Ext.Msg.OK,   
			       		icon : Ext.Msg.ERROR   
		   			});  
		   			httpReq=null;
		   		}
		   	}
		}
	}
	
	/**
	 * 表单验证
	 */
	function saveValidate(){
		if(Ext.getCmp("cName").getValue()==""){
			Ext.getCmp("cName").markInvalid("费用名称不能为空");
			return false;
		}
		
		if(!newType.disabled && newType.getValue()=="") {
			newType.markInvalid("费用分类不能为空");
			return false;
		} else if(newType.disabled && Ext.getCmp("type").getValue()==""){
			Ext.getCmp("type").markInvalid("费用分类不能为空");
			return false;
		}
		
		if(Ext.getCmp("amount").getValue()==""){
			Ext.getCmp("amount").markInvalid("金额不能为空");
			return false;
		}
		
		var amount = Ext.getCmp("amount").getValue() + "";
		
		if(amount.length>13){
			Ext.getCmp("amount").markInvalid("金额长度不能超过13位");
			return false;
		}
				
		if(Ext.getCmp("occurDate").getValue()==""){
			Ext.getCmp("occurDate").markInvalid("发生时间不能为空");
			return false;
		}
		return true;
	}
	
	store.on('beforeload',function(thiz,options){
		mainPanel.body.mask('正在加载数据','x-mask-loading');
		options.params.param_2 = 105;	
    });
    
	store.on("load",function(){
		mainPanel.body.unmask();
	});
	
	store.load({
        params: {
            param_0: 0,
            param_1: 20,
            param_2: 105
        }
    });
});